package com.yupixm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupixm.common.ErrorCode;
import com.yupixm.contants.UserConstant;
import com.yupixm.exception.BusinessException;
import com.yupixm.mapper.UserMapper;
import com.yupixm.pojo.domain.User;
import com.yupixm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author su
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2022-07-08 16:21:18
 */
@Service
@Slf4j //记录日志
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;  //报错原因是无找到实现类，可以不用管

    //盐值，用于混淆密码加密
    private static final String SALT = "yupi";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1 校验
        //注意 StringUtils 使用的是apache 的commons-lang3
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"数据有空值");
        }
        if (userAccount.length() > 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账户大于4位");
        }
        if (userPassword.length() > 8 || checkPassword.length() > 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名密码小于8位");
        }

        //账户名不能包含特殊字符
        String regEx = ".*[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*()——+|{}【】‘；：”“’。，、？\\\\]+.*";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名不能包含特殊字符");
        }
        //密码与校验密码要相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码与校验密码要相同");
        }
        //用户名不能重复
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("userAccount", userAccount);
        int count = this.count(qw);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名不能重复");
        }
        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //登录
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"登录失败");
        }


        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1 校验
        //注意 StringUtils 使用的是apache 的commons-lang3
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"数据有空值");
        }
        if (userAccount.length() > 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账户大于4位");
        }
        if (userPassword.length() > 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名密码小于8位");
        }
        //账户名不能包含特殊字符
        String regEx = ".*[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*()——+|{}【】‘；：”“’。，、？\\\\]+.*";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户名不能包含特殊字符");
        }
        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("userAccount", userAccount);
        //加密后的密码是否相同
        qw.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(qw);
        //用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NULL_ERROR,"用户不存在");
        }
        //用户脱敏
        User safetyUser = getSafetyUser(user);
        //记录用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,safetyUser);
        return safetyUser;
    }


    /**
     * @param request
     * @return
     */
    public int userLogout(HttpServletRequest request){
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }

    /**
     *  用户脱敏
     * @param origianUser
     * @return 脱敏后的用户信息
     * author su
     */
    @Override
    public User getSafetyUser(User origianUser){
        //避免传入空对象
        if (origianUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"用户为空");
        }
        User safetyUser = new User();
        safetyUser.setId(origianUser.getId());
        safetyUser.setUserName(origianUser.getUserName());
        safetyUser.setUserAccount(origianUser.getUserAccount());
        safetyUser.setAvatarUrl(origianUser.getAvatarUrl());
        safetyUser.setGender(0);
        safetyUser.setPhone(origianUser.getPhone());
        safetyUser.setEmail(origianUser.getEmail());
        safetyUser.setUserStatus(0);
        safetyUser.setCreateTime(origianUser.getCreateTime());
        safetyUser.setUserRole(origianUser.getUserRole());
        return safetyUser;
    }
}




